import { useEffect } from "react";
import useMediaQuery from "@hooks/useMediaQuery";
import { useLocalStorage } from "@hooks/useStorage";

type UseDarkModeReturn = [boolean, (value: boolean) => void];

export default function useDarkMode(): UseDarkModeReturn {
  const [darkMode, setDarkMode] = useLocalStorage("useDarkMode", false);
  const prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
  const enabled = darkMode ?? prefersDarkMode;

  useEffect(() => {
    document.body.classList.toggle("dark-mode", enabled);
  }, [enabled]);

  const toggleDarkMode = (value: boolean) => {
    setDarkMode(value);
  };

  return [enabled, toggleDarkMode];
}
